package com.aivin.lint_lib_java.detector;

import com.aivin.lint_lib_java.JavaLog;
import com.android.resources.ResourceFolderType;
import com.android.tools.lint.detector.api.Category;
import com.android.tools.lint.detector.api.Detector;
import com.android.tools.lint.detector.api.Implementation;
import com.android.tools.lint.detector.api.Issue;
import com.android.tools.lint.detector.api.Location;
import com.android.tools.lint.detector.api.ResourceContext;
import com.android.tools.lint.detector.api.Scope;
import com.android.tools.lint.detector.api.Severity;

/**
 * 定义代码检查规则
 * 这个是针对项目中的图片大小的一个判断，超过250kb的全部提醒出来，让他们压缩
 * </p>
 */
public class AVImageFileSizeDetector extends Detector implements Detector.BinaryResourceScanner {

    public static final Issue ISSUE = Issue.create(
            "XTC_ImageFileSizeInvalid",
            "图片文件过大",
            "图片文件过大，请压缩你的图片文件。图片压缩方案可以参考: https://github.com/qjoy/TinyPNGNodeJSBatcher",
            Category.CORRECTNESS,
            5,
            Severity.ERROR,
            new Implementation(  AVImageFileSizeDetector.class,  Scope.BINARY_RESOURCE_FILE_SCOPE    )
    ).addMoreInfo("https://github.com/qjoy/TinyPNGNodeJSBatcher");


    @Override
    public boolean appliesTo(ResourceFolderType var1) {
        return true;
    }

    @Override
    public void checkBinaryResource(ResourceContext context) {
        ResourceFolderType folderType = context.getResourceFolderType();
        if (folderType != null && (folderType == ResourceFolderType.MIPMAP || folderType == ResourceFolderType.DRAWABLE)) {
            String filename = context.file.getName();
            if (filename.contains( ".png")
                    || filename.contains(".jpeg")
                    || filename.contains(".jpg")) {
                long fileSize = context.file.length() / 1024;

                int  CHECK_IMAGE_KB_SIZE = 200;
                String reportStr = "图片文件过大: %d" + "KB,超过了项目限制的:" + CHECK_IMAGE_KB_SIZE + "KB,请进行图片压缩或找UI工程师重新设计出图.";

                if (fileSize > CHECK_IMAGE_KB_SIZE) {
                    String repS = String.format(reportStr, fileSize);
                    Location fileLocation = Location.create(context.file);
                    context.report(ISSUE, fileLocation, repS);
                    JavaLog.showLog("检测到过大的图片 "+filename);
                }
            }
        }
    }
}
